package com.i2863.shiroDemo.web;

import com.i2863.shiroDemo.dto.PermissionInfo;
import com.i2863.shiroDemo.dto.ResultInfo;
import com.i2863.shiroDemo.entity.Permission;
import com.i2863.shiroDemo.entity.Role;
import com.i2863.shiroDemo.service.IPermissionService;
import com.i2863.shiroDemo.service.IRoleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * PermissionController
 *
 * @author cexy
 * @description:
 * @date 2020/10/23
 * @time 18:05
 */
@Controller
@RequestMapping("permission")
public class PermissionController extends BaseController {

    @Resource
    private IPermissionService permService;
    @Resource
    private IRoleService roleService;

    @ResponseBody
    @RequestMapping("menu/xtree/{roleId}")
    public ResultInfo<List<PermissionInfo>> xtreeData(@PathVariable int roleId) {
        Permission superPerm = this.getSuperPermission();
        Role role = roleService.getById(roleId);
        String perStr = role.getPermissionIds();
        List<PermissionInfo> permissionInfos = permService.getCurrentUserPermissionMenu(this.getUserInfo().getRoleInfo());
        if (perStr == null) {
            permissionInfos.forEach(permissionInfo -> {
                permissionInfo.setChecked(false);
                permissionInfo.getData().forEach(permissionInfo1 -> {
                    permissionInfo1.setChecked(false);
                    permissionInfo1.getData().forEach(permissionInfo2 -> permissionInfo2.setChecked(false));
                });
            });
            return new ResultInfo<>(permissionInfos);
        }
        if (perStr.contains("," + superPerm.getId() + ",")) {
            return new ResultInfo<>(permissionInfos);
        }
        permissionInfos.forEach(permissionInfo -> {
            permissionInfo.setChecked(perStr.contains("," + permissionInfo.getValue() + ","));
            if (perStr.contains("," + permissionInfo.getValue() + ",")) {
                permissionInfo.getData().forEach(permissionInfo1 -> {
                    permissionInfo1.setChecked(perStr.contains("," + permissionInfo1.getValue() + ","));
                    if (perStr.contains("," + permissionInfo1.getValue() + ",")) {
                        permissionInfo1.getData().forEach(permissionInfo2 -> {
                                    permissionInfo2.setChecked(perStr.contains("," + permissionInfo2.getValue() + ","));
                                    permissionInfo2.getData().forEach(permissionInfo3 -> permissionInfo3.setChecked(perStr.contains("," + permissionInfo3.getValue() + ",")));
                                }
                        );
                    }
                });
            }
        });
        return new ResultInfo<>(permissionInfos);
    }
}
